#include <iostream>
#include "RingBuffer.hpp"
#include <unistd.h>

using namespace RingBufferModule;

int global_data = 0;
MutexModule::Mutex data_mutex;
MutexModule::Mutex print_mutex;

void *Consumer(void *args)
{
    RingBuffer<int> *ring_buffer = static_cast<RingBuffer<int> *>(args);
    while (true)
    {
        sleep(1);
        // 1,消费数据
        int data;
        ring_buffer->Pop(&data);

        {
            MutexModule::LockGuard print_guard(print_mutex);
            // 2,处理：花时间
            std::cout << "消费了一个数据：" << data << std::endl;
        }
    }
}

void *Productor(void *args)
{
    RingBuffer<int> *ring_buffer = static_cast<RingBuffer<int> *>(args);

    while (true)
    {
        // 获取数据：花时间
        sleep(1);

        int local_data;
        {
            MutexModule::LockGuard data_guard(data_mutex);
            local_data = global_data++;
        }

        // 1,生产数据
        ring_buffer->Enqueue(local_data);

        // 2,处理：花时间
        {
            MutexModule::LockGuard print_guard(print_mutex);
            std::cout << "生产了一个数据: " << local_data << std::endl;
        }
    }
}

int main()
{
    RingBuffer<int> *ring_buffer = new RingBuffer<int>(5);

    pthread_t c1, p1, c2, c3, p2;
    pthread_create(&c1, nullptr, Consumer, ring_buffer);
    pthread_create(&p1, nullptr, Productor, ring_buffer);
    pthread_create(&c2, nullptr, Consumer, ring_buffer);
    pthread_create(&c3, nullptr, Consumer, ring_buffer);
    pthread_create(&p2, nullptr, Productor, ring_buffer);

    pthread_join(c1, nullptr);
    pthread_join(p1, nullptr);
    pthread_join(c2, nullptr);
    pthread_join(p2, nullptr);
    pthread_join(c3, nullptr);

    delete ring_buffer;

    return 0;
}